<!-- 异常处理页 -->
<template>
  <div class="app-container font-inter bg-gray-50 text-dark min-h-screen flex flex-col">
    <div class="flex flex-1 pt-16">
      <!-- 主内容区 -->
      <main class="flex-1 p-4 md:p-6 transition-all duration-300">
        <!-- 页面标题和操作按钮 -->
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
          <div class="flex gap-3">
            <button id="add-exception-btn" class="btn-primary flex items-center gap-2" @click="openAddExceptionModal">
              <i class="fa fa-plus"></i>
              <span>新建异常报告</span>
            </button>
          </div>
        </div>
        <!-- 筛选和搜索 -->
        <div class="bg-white rounded-xl p-4 mb-6 card-shadow">
          <div class="flex flex-col md:flex-row gap-4">
            <div class="flex-1">
              <div class="relative">
                <input type="text" id="search-input" placeholder="搜索异常报告(标题/编号/报告人)..."
                  class="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                  v-model="searchText" @keyup.enter="applyFilters">
                <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-secondary"></i>
              </div>
            </div>
            <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
              <select id="status-filter"
                class="border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                v-model="statusFilter">
                <option value="all">所有状态</option>
                <option value="待处理">待处理</option>
                <option value="处理中">处理中</option>
                <option value="已解决">已解决</option>
              </select>
              <select id="type-filter"
                class="border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                v-model="typeFilter">
                <option value="all">所有类型</option>
                <option value="设备故障">设备故障</option>
                <option value="质量问题">质量问题</option>
                <option value="物料短缺">物料短缺</option>
                <option value="人员问题">人员问题</option>
              </select>
              <select id="dept-filter"
                class="border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                v-model="deptFilter">
                <option value="all">所有部门</option>
                <option value="生产一部">生产一部</option>
                <option value="生产二部">生产二部</option>
                <option value="质检部">质检部</option>
                <option value="仓储部">仓储部</option>
              </select>
              <button id="filter-btn" class="btn-outline" @click="applyFilters">
                <i class="fa fa-filter mr-1"></i> 筛选
              </button>
            </div>
          </div>
        </div>
        <!-- 异常报告列表 -->
        <div class="bg-white rounded-xl p-4 md:p-6 mb-6 card-shadow">
          <div class="overflow-x-auto">
            <table class="w-full min-w-[800px]">
              <thead>
                <tr class="border-b border-gray-100">
                  <th class="text-left py-3 px-4 font-medium text-secondary">报告编号</th>
                  <th class="text-left py-3 px-4 font-medium text-secondary">异常标题</th>
                  <th class="text-left py-3 px-4 font-medium text-secondary">异常类型</th>
                  <th class="text-left py-3 px-4 font-medium text-secondary">发生时间</th>
                  <th class="text-left py-3 px-4 font-medium text-secondary">状态</th>
                  <th class="text-left py-3 px-4 font-medium text-secondary">报告人</th>
                  <th class="text-left py-3 px-4 font-medium text-secondary">操作</th>
                </tr>
              </thead>
              <tbody id="exception-table-body">
                <tr v-if="filteredReports.length === 0">
                  <td colspan="7" class="py-12 text-center">
                    <div class="w-16 h-16 mx-auto mb-4 rounded-full bg-gray-100 flex items-center justify-center">
                      <i class="fa fa-search-minus text-2xl text-secondary"></i>
                    </div>
                    <p class="text-secondary">未找到符合条件的异常报告</p>
                    <button id="reset-filter-btn" class="mt-4 btn-outline" @click="resetFilters">
                      <i class="fa fa-refresh mr-1"></i> 重置筛选
                    </button>
                  </td>
                </tr>
                <tr v-for="report in filteredReports" :key="report.id"
                  class="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                  <td class="py-3 px-4 font-medium">{{ report.id }}</td>
                  <td class="py-3 px-4">{{ report.title }}</td>
                  <td class="py-3 px-4">{{ report.type }}</td>
                  <td class="py-3 px-4">{{ report.time }}</td>
                  <td class="py-3 px-4">
                    <span class="px-2 py-1 rounded-full text-sm" :class="{
                      'bg-red-50 text-red-600': report.status === '待处理',
                      'bg-yellow-50 text-yellow-600': report.status === '处理中',
                      'bg-green-50 text-green-600': report.status === '已解决'
                    }">
                      {{ report.status }}
                    </span>
                  </td>
                  <td class="py-3 px-4">{{ report.reporter }}</td>
                  <td class="py-3 px-4">
                    <button class="text-primary hover:text-primary/80 p-1 view-detail-btn"
                      @click="showExceptionDetail(report)">
                      <i class="fa fa-eye"></i>
                    </button>
                    <button class="text-secondary hover:text-dark p-1 ml-1 edit-btn" @click="editException(report)">
                      <i class="fa fa-pencil"></i>
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <!-- 统计信息 -->
          <div id="report-stats" class="flex items-center justify-between mt-6 text-secondary">
            <div id="total-count">共 <span class="font-medium text-primary">{{ filteredReports.length }}</span> 条异常报告
            </div>
            <div id="load-status" class="text-sm">{{ filteredReports.length > 0 ? '已加载全部数据' : '暂无数据' }}</div>
          </div>
        </div>
        <!-- 异常类型统计 -->
        <div class="p-4">
          <div class="mt-8 p-4 bg-light rounded-lg" style="width:500px">
            <h3 class="font-medium mb-3">异常类型分布</h3>
            <canvas ref="exceptionChart" width="200" height="200"></canvas>
          </div>
        </div>
      </main>
    </div>
    <!-- 异常报告详情模态框 -->
    <div id="exception-detail-modal" class="fixed inset-0 z-50 flex items-center justify-center"
      :class="{ 'hidden': !showDetailModal }" v-show="showDetailModal">
      <div class="absolute inset-0 bg-black/50" @click="closeDetailModal"></div>
      <div
        class="bg-white rounded-xl w-full max-w-4xl max-h-[90vh] overflow-y-auto relative z-10 transform transition-all">
        <div class="p-6 border-b border-gray-100 flex items-center justify-between">
          <h3 class="text-xl font-semibold" id="detail-modal-title">异常报告详情</h3>
          <button id="close-detail-modal" class="text-secondary hover:text-dark p-2" @click="closeDetailModal">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
        <div class="p-6" v-if="currentReport">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div>
              <h4 class="text-sm text-secondary mb-1">报告编号</h4>
              <p class="font-medium" id="detail-report-id">#{{ currentReport.id }}</p>
            </div>
            <div>
              <h4 class="text-sm text-secondary mb-1">异常标题</h4>
              <p class="font-medium" id="detail-title">{{ currentReport.title }}</p>
            </div>
            <div>
              <h4 class="text-sm text-secondary mb-1">异常类型</h4>
              <p class="font-medium" id="detail-type">{{ currentReport.type }}</p>
            </div>
            <div>
              <h4 class="text-sm text-secondary mb-1">发生时间</h4>
              <p class="font-medium" id="detail-time">{{ currentReport.time }}</p>
            </div>
            <div>
              <h4 class="text-sm text-secondary mb-1">发生部门</h4>
              <p class="font-medium" id="detail-department">{{ currentReport.department }}</p>
            </div>
            <div>
              <h4 class="text-sm text-secondary mb-1">状态</h4>
              <p class="font-medium" id="detail-status">
                <span class="px-2 py-1 rounded-full text-sm" :class="{
                  'bg-red-50 text-red-600': currentReport.status === '待处理',
                  'bg-yellow-50 text-yellow-600': currentReport.status === '处理中',
                  'bg-green-50 text-green-600': currentReport.status === '已解决'
                }">
                  {{ currentReport.status }}
                </span>
              </p>
            </div>
            <div>
              <h4 class="text-sm text-secondary mb-1">报告人</h4>
              <p class="font-medium" id="detail-reporter">{{ currentReport.reporter }}</p>
            </div>
            <div>
              <h4 class="text-sm text-secondary mb-1">负责人</h4>
              <p class="font-medium" id="detail-manager">{{ currentReport.manager || '未分配' }}</p>
            </div>
          </div>
          <div class="mb-6">
            <h4 class="text-sm text-secondary mb-2">异常描述</h4>
            <div class="p-4 bg-light rounded-lg" id="detail-description">
              <p>{{ currentReport.description }}</p>
            </div>
          </div>
          <div class="mb-6">
            <h4 class="text-sm text-secondary mb-2">异常图片</h4>
            <div class="grid grid-cols-1 sm:grid-cols-3 gap-3" id="detail-images">
              <div v-if="currentReport.images.length === 0" class="text-secondary">暂无图片</div>
              <div v-for="(img, index) in currentReport.images" :key="index" class="relative group">
                <img :src="img" alt="异常图片" class="w-full h-32 object-cover rounded-lg">
                <div
                  class="absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity rounded-lg">
                  <button class="text-white p-2 enlarge-btn">
                    <i class="fa fa-search-plus text-xl"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div class="mb-6">
            <h4 class="text-sm text-secondary mb-2">影响评估</h4>
            <div class="p-4 bg-light rounded-lg" id="detail-impact">
              <p>{{ currentReport.impact }}</p>
            </div>
          </div>
          <div class="mb-6">
            <h4 class="text-sm text-secondary mb-2">处理方案</h4>
            <div class="p-4 bg-light rounded-lg" id="detail-solution">
              <p v-for="(line, index) in currentReport.solution.split('\n')" :key="index">{{ line }}</p>
            </div>
          </div>
          <div class="mb-6">
            <h4 class="text-sm text-secondary mb-2">生产计划调整</h4>
            <div class="p-4 bg-light rounded-lg">
              <p id="detail-plan-adjust">{{ currentReport.planAdjust || '暂无生产计划调整' }}</p>
              <button id="adjust-plan-btn" class="mt-3 text-primary hover:text-primary/80 flex items-center gap-1"
                @click="openPlanAdjustModal">
                <i class="fa fa-calendar-check-o"></i>
                <span>调整生产计划</span>
              </button>
            </div>
          </div>
          <div class="mb-6">
            <h4 class="text-sm text-secondary mb-2">处理记录</h4>
            <div class="space-y-4" id="detail-process-records">
              <div v-if="currentReport.records.length === 0" class="text-secondary text-center py-4">暂无处理记录</div>
              <div v-for="(record, index) in currentReport.records" :key="index" class="p-4 bg-light rounded-lg">
                <div class="flex justify-between items-start mb-2">
                  <div class="font-medium">{{ record.name }}</div>
                  <div class="text-xs text-secondary">{{ record.time }}</div>
                </div>
                <p>{{ record.content }}</p>
              </div>
            </div>
          </div>
          <div class="flex justify-end gap-3 pt-4 border-t border-gray-100">
            <button id="close-detail-btn" class="btn-outline" @click="closeDetailModal">关闭</button>
            <button id="edit-exception-btn" class="btn-primary" @click="editException(currentReport)">编辑报告</button>
          </div>
        </div>
      </div>
    </div>
    <!-- 新建/编辑异常报告模态框 -->
    <div id="exception-form-modal" class="fixed inset-0 z-50 flex items-center justify-center"
      :class="{ 'hidden': !showFormModal }" v-show="showFormModal">
      <div class="absolute inset-0 bg-black/50" @click="closeFormModal"></div>
      <div
        class="bg-white rounded-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto relative z-10 transform transition-all">
        <div class="p-6 border-b border-gray-100 flex items-center justify-between">
          <h3 class="text-xl font-semibold" id="form-modal-title">{{ isEditMode ? '编辑异常报告' : '新建异常报告' }}</h3>
          <button id="close-form-modal" class="text-secondary hover:text-dark p-2" @click="closeFormModal">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
        <div class="p-6">
          <form id="exception-form" @submit.prevent="submitExceptionForm">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
              <div>
                <label for="form-title" class="block text-sm text-secondary mb-1">异常标题*</label>
                <input type="text" id="form-title"
                  class="w-full border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                  required v-model="formModel.title">
              </div>
              <div>
                <label for="form-type" class="block text-sm text-secondary mb-1">异常类型*</label>
                <select id="form-type"
                  class="w-full border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                  required v-model="formModel.type">
                  <option value="">请选择异常类型</option>
                  <option value="设备故障">设备故障</option>
                  <option value="质量问题">质量问题</option>
                  <option value="物料短缺">物料短缺</option>
                  <option value="人员问题">人员问题</option>
                  <option value="其他">其他</option>
                </select>
              </div>
              <div>
                <label for="form-department" class="block text-sm text-secondary mb-1">发生部门*</label>
                <select id="form-department"
                  class="w-full border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                  required v-model="formModel.department">
                  <option value="">请选择部门</option>
                  <option value="生产一部">生产一部</option>
                  <option value="生产二部">生产二部</option>
                  <option value="质检部">质检部</option>
                  <option value="仓储部">仓储部</option>
                  <option value="其他">其他</option>
                </select>
              </div>
              <div>
                <label for="form-time" class="block text-sm text-secondary mb-1">发生时间*</label>
                <input type="datetime-local" id="form-time"
                  class="w-full border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                  required v-model="formModel.time">
              </div>
            </div>
            <div class="mb-6">
              <label for="form-description" class="block text-sm text-secondary mb-1">异常描述*</label>
              <textarea id="form-description" rows="4"
                class="w-full border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                required v-model="formModel.description"></textarea>
            </div>
            <div class="mb-6">
              <label class="block text-sm text-secondary mb-1">上传图片</label>
              <div class="border-2 border-dashed border-gray-200 rounded-lg p-4 text-center">
                <div class="flex flex-col items-center justify-center py-4">
                  <i class="fa fa-cloud-upload text-3xl text-secondary mb-2"></i>
                  <p class="text-sm text-secondary mb-2">拖放文件到此处或点击上传</p>
                  <button type="button" id="upload-btn" class="btn-outline text-sm px-3 py-1">
                    <i class="fa fa-folder-open mr-1"></i> 选择文件
                  </button>
                </div>
                <div class="grid grid-cols-3 gap-2" id="upload-preview">
                  <!-- 上传图片预览 -->
                </div>
              </div>
            </div>
            <div class="mb-6">
              <label for="form-impact" class="block text-sm text-secondary mb-1">影响评估</label>
              <textarea id="form-impact" rows="3"
                class="w-full border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                v-model="formModel.impact"></textarea>
            </div>
            <div class="mb-6">
              <label for="form-solution" class="block text-sm text-secondary mb-1">初步处理方案</label>
              <textarea id="form-solution" rows="3"
                class="w-full border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                v-model="formModel.solution"></textarea>
            </div>
            <div class="flex justify-end gap-3 pt-4 border-t border-gray-100">
              <button type="button" id="cancel-form-btn" class="btn-outline" @click="closeFormModal">取消</button>
              <button type="submit" class="btn-primary">提交报告</button>
            </div>
          </form>
        </div>
      </div>
    </div>
    <!-- 生产计划调整模态框 -->
    <div id="plan-adjust-modal" class="fixed inset-0 z-50 flex items-center justify-center"
      :class="{ 'hidden': !showPlanAdjustModal }" v-show="showPlanAdjustModal">
      <div class="absolute inset-0 bg-black/50" @click="closePlanAdjustModal"></div>
      <div
        class="bg-white rounded-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto relative z-10 transform transition-all">
        <div class="p-6 border-b border-gray-100 flex items-center justify-between">
          <h3 class="text-xl font-semibold">调整生产计划</h3>
          <button id="close-plan-modal" class="text-secondary hover:text-dark p-2" @click="closePlanAdjustModal">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
        <div class="p-6">
          <form id="plan-adjust-form">
            <div class="mb-6">
              <label for="adjust-plan-id" class="block text-sm text-secondary mb-1">关联生产计划*</label>
              <select id="adjust-plan-id"
                class="w-full border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                required>
                <option value="">请选择生产计划</option>
                <option value="PL-2023-0615-A">PL-2023-0615-A (A批次产品)</option>
                <option value="PL-2023-0615-B">PL-2023-0615-B (B批次产品)</option>
                <option value="PL-2023-0615-C">PL-2023-0615-C (C批次产品)</option>
              </select>
            </div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
              <div>
                <label for="adjust-original-time" class="block text-sm text-secondary mb-1">原计划时间*</label>
                <input type="datetime-local" id="adjust-original-time"
                  class="w-full border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                  disabled>
              </div>
              <div>
                <label for="adjust-new-time" class="block text-sm text-secondary mb-1">调整后时间*</label>
                <input type="datetime-local" id="adjust-new-time"
                  class="w-full border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                  required>
              </div>
            </div>
            <div class="mb-6">
              <label for="adjust-reason" class="block text-sm text-secondary mb-1">调整原因*</label>
              <textarea id="adjust-reason" rows="3"
                class="w-full border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                required></textarea>
            </div>
            <div class="mb-6">
              <label for="adjust-notice" class="block text-sm text-secondary mb-1">通知人员</label>
              <div class="flex flex-wrap gap-2 mb-2" id="selected-contacts">
                <!-- 已选联系人标签 -->
              </div>
              <div class="relative">
                <input type="text" id="adjust-notice" placeholder="搜索并添加通知人员..."
                  class="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary">
                <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-secondary"></i>
                <div id="contact-dropdown"
                  class="absolute left-0 right-0 top-full mt-1 bg-white rounded-lg shadow-lg z-10 hidden max-h-60 overflow-y-auto">
                  <!-- 联系人列表由JS动态生成 -->
                </div>
              </div>
            </div>
            <div class="flex justify-end gap-3 pt-4 border-t border-gray-100">
              <button type="button" id="cancel-plan-btn" class="btn-outline" @click="closePlanAdjustModal">取消</button>
              <button type="submit" class="btn-primary">提交调整</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { Chart, registerables } from 'chart.js'

Chart.register(...registerables)

const router = useRouter()

// 响应式数据
const showDetailModal = ref(false)
const showFormModal = ref(false)
const showPlanAdjustModal = ref(false)
const isEditMode = ref(false)
const currentReport = ref(null)
const searchText = ref('')
const statusFilter = ref('all')
const typeFilter = ref('all')
const deptFilter = ref('all')
const exceptionChart = ref(null)

// 表单数据模型
const formModel = reactive({
  title: '',
  type: '',
  department: '',
  time: '',
  description: '',
  impact: '',
  solution: ''
})

// 异常报告数据
const exceptionReports = ref([
  {
    id: 'EXC-2023-0567',
    title: '包装机封口温度异常',
    type: '设备故障',
    time: '2023-06-15 08:32',
    status: '处理中',
    reporter: '张明',
    department: '生产一部',
    manager: '李强 (设备维护部)',
    description: '包装机型号为P-2000的设备在今日早班生产时出现封口温度不稳定现象，温度波动范围在180℃-220℃之间（标准应为200±5℃），导致约10%的产品包装密封不良，需要返工处理。',
    impact: '目前已影响约200件产品质量，预计会导致生产线暂停2小时进行维修，可能影响今日A批次产品的交付时间。',
    solution: '1. 立即停机检查温度传感器和加热元件\n2. 更换损坏的温度传感器\n3. 重新校准设备温度控制系统\n4. 对已生产的产品进行全面质检',
    planAdjust: '由于设备维修需要，原计划今日上午10点开始的B批次生产将推迟至下午2点开始，相关人员已通知到位。',
    images: [
      'https://picsum.photos/id/1018/400/300',
      'https://picsum.photos/id/1015/400/300'
    ],
    records: [
      { name: '李强', time: '2023-06-15 09:15', content: '已初步检查设备，发现温度传感器读数不稳定，可能是传感器老化导致。已联系备件仓库准备更换零件。' },
      { name: '王芳', time: '2023-06-15 10:30', content: '已更换温度传感器，正在进行设备校准。预计还需要1小时完成全部调试工作。' }
    ]
  },
  {
    id: 'EXC-2023-0566',
    title: '产品尺寸偏差超标',
    type: '质量问题',
    time: '2023-06-14 14:20',
    status: '已解决',
    reporter: '王芳',
    department: '质检部',
    manager: '赵伟 (质量部)',
    description: '在今日下午的例行抽检中发现，批次号为B-0614的产品尺寸偏差超出允许范围(标准±0.5mm，实际测量±0.8mm)，已暂停该批次产品发货。',
    impact: '影响B-0614批次共500件产品，需要全检并返工不合格品，预计延迟发货1天。',
    solution: '1. 暂停生产线并排查原因\n2. 调整设备参数\n3. 对已生产产品进行全检\n4. 隔离不合格品并返工',
    planAdjust: '原定今日发货的B-0614批次将推迟至明天发货，客户已通知并获得理解。',
    images: [
      'https://picsum.photos/id/1020/400/300'
    ],
    records: [
      { name: '赵伟', time: '2023-06-14 15:30', content: '已确认是设备参数设置错误导致，已重新设置并试生产，产品尺寸恢复正常。' },
      { name: '王芳', time: '2023-06-14 16:45', content: '已完成全检，不合格率为12%，不合格品已隔离并安排返工。' }
    ]
  },
  {
    id: 'EXC-2023-0565',
    title: '关键物料库存不足',
    type: '物料短缺',
    time: '2023-06-13 09:05',
    status: '已解决',
    reporter: '李强',
    department: '仓储部',
    manager: '张明 (采购部)',
    description: '检查发现生产A产品所需的关键物料X-100库存仅剩200件，低于安全库存300件，而本周生产计划需要500件。',
    impact: '如果不及时补充，将在2天后影响A产品的正常生产，可能导致生产线停工。',
    solution: '1. 联系供应商紧急调货\n2. 调整生产计划优先使用现有库存\n3. 检查其他替代物料可能性',
    planAdjust: '将原定周四开始的A产品生产提前至周二，以利用现有库存，同时等待补充物料到达。',
    images: [],
    records: [
      { name: '张明', time: '2023-06-13 10:20', content: '已联系供应商，可于明日紧急发货300件，剩余200件将在周五前送达。' },
      { name: '李强', time: '2023-06-13 11:15', content: '已调整库存分配计划，确保关键生产线优先使用。' }
    ]
  },
  {
    id: 'EXC-2023-0564',
    title: '生产线人员短缺',
    type: '人员问题',
    time: '2023-06-12 07:50',
    status: '已解决',
    reporter: '赵伟',
    department: '生产二部',
    manager: '王芳 (人力资源部)',
    description: '今日早班生产二部有3名员工因病请假，导致生产线人员不足，无法同时运行两条生产线。',
    impact: '生产效率将降低约40%，今日产量可能无法达到目标。',
    solution: '1. 从其他部门临时调配人员\n2. 调整生产计划集中生产高优先级产品\n3. 安排加班补足产量',
    planAdjust: '将原计划今日生产的C产品推迟至明天，集中生产B产品以满足紧急订单需求。',
    images: [],
    records: [
      { name: '王芳', time: '2023-06-12 08:30', content: '已从质检部临时调配2名员工支援生产线，并安排1名实习生协助。' },
      { name: '赵伟', time: '2023-06-12 16:00', content: '今日产量达到目标的85%，剩余部分将通过明日早班加班完成。' }
    ]
  },
  {
    id: 'EXC-2023-0563',
    title: '设备润滑系统故障',
    type: '设备故障',
    time: '2023-06-10 13:15',
    status: '待处理',
    reporter: '张明',
    department: '生产一部',
    manager: '',
    description: 'M-200型号加工中心的自动润滑系统报警，检查发现润滑油泵工作异常，可能导致设备润滑不足。',
    impact: '如果继续运行可能造成设备磨损，建议立即停机检查。',
    solution: '1. 停机检查润滑系统\n2. 联系设备供应商技术支持\n3. 准备备用设备',
    planAdjust: '',
    images: [
      'https://picsum.photos/id/103/400/300',
      'https://picsum.photos/id/104/400/300'
    ],
    records: []
  },
  {
    id: 'EXC-2023-0562',
    title: '原材料质量不达标',
    type: '质量问题',
    time: '2023-06-09 10:18',
    status: '处理中',
    reporter: '刘红',
    department: '质检部',
    manager: '赵伟 (质量部)',
    description: '今日入库的批次为RM-0609的原材料，检测发现纯度仅为98.2%，低于标准要求的99.5%，不符合生产使用标准。',
    impact: '影响后续3个批次产品的生产，涉及产品数量约1200件，可能导致生产计划延误。',
    solution: '1. 隔离不合格原材料\n2. 联系供应商退换货\n3. 启用备用原材料库存\n4. 加强后续原材料抽检频率',
    planAdjust: '将原计划6月10日开始的A批次生产推迟至6月12日，待合格原材料到位后再启动。',
    images: [
      'https://picsum.photos/id/105/400/300'
    ],
    records: [
      { name: '赵伟', time: '2023-06-09 11:30', content: '已联系供应商，对方同意3日内更换合格原材料，同时提供10%的补货补偿。' },
      { name: '刘红', time: '2023-06-09 14:20', content: '已完成不合格原材料的隔离存放，并标记禁用标识。' }
    ]
  },
  {
    id: 'EXC-2023-0561',
    title: '车间电力供应不稳',
    type: '其他',
    time: '2023-06-08 09:45',
    status: '已解决',
    reporter: '陈明',
    department: '生产一部',
    manager: '张伟 (工程部)',
    description: '今日上午生产车间出现3次短暂停电（每次持续10-20秒），导致正在运行的3台设备紧急停机，部分在制品损坏。',
    impact: '损坏在制品约50件，设备重启调试耗时1.5小时，影响今日上午生产进度约20%。',
    solution: '1. 联系电力公司检查线路\n2. 检查车间内部配电系统\n3. 为关键设备配备UPS应急电源\n4. 制定设备紧急停机操作规程',
    planAdjust: '通过延长今日下午工作时间1小时，弥补上午损失的生产进度，确保当日产量达标。',
    images: [
      'https://picsum.photos/id/106/400/300',
      'https://picsum.photos/id/107/400/300'
    ],
    records: [
      { name: '张伟', time: '2023-06-08 11:20', content: '电力公司已修复外部线路故障，车间内部配电系统检查正常，已安排明日安装UPS电源。' },
      { name: '陈明', time: '2023-06-08 16:30', content: '已完成设备调试和在制品清理，通过延长工作时间已弥补生产进度，今日产量达标。' }
    ]
  }
])

// 计算属性
const filteredReports = computed(() => {
  let result = [...exceptionReports.value]

  if (statusFilter.value !== 'all') {
    result = result.filter(report => report.status === statusFilter.value)
  }

  if (typeFilter.value !== 'all') {
    result = result.filter(report => report.type === typeFilter.value)
  }

  if (deptFilter.value !== 'all') {
    result = result.filter(report => report.department === deptFilter.value)
  }

  if (searchText.value) {
    const search = searchText.value.toLowerCase()
    result = result.filter(report =>
      report.title.toLowerCase().includes(search) ||
      report.id.toLowerCase().includes(search) ||
      report.reporter.toLowerCase().includes(search)
    )
  }

  return result
})

// 方法
const showExceptionDetail = (report) => {
  currentReport.value = report
  showDetailModal.value = true
}

const closeDetailModal = () => {
  showDetailModal.value = false
  currentReport.value = null
}

const openAddExceptionModal = () => {
  isEditMode.value = false
  // 重置表单
  formModel.title = ''
  formModel.type = ''
  formModel.department = ''
  formModel.time = ''
  formModel.description = ''
  formModel.impact = ''
  formModel.solution = ''
  showFormModal.value = true
}

const editException = (report) => {
  isEditMode.value = true
  // 填充表单数据
  formModel.title = report.title
  formModel.type = report.type
  formModel.department = report.department
  formModel.time = report.time.replace(' ', 'T').substring(0, 16)
  formModel.description = report.description
  formModel.impact = report.impact
  formModel.solution = report.solution
  showFormModal.value = true
}

const closeFormModal = () => {
  showFormModal.value = false
}

const submitExceptionForm = () => {
  if (isEditMode.value) {
    // 编辑模式：找到对应报告并更新
    const reportIndex = exceptionReports.value.findIndex(r => r.id === currentReport.value.id)
    if (reportIndex !== -1) {
      exceptionReports.value[reportIndex] = {
        ...exceptionReports.value[reportIndex],
        title: formModel.title,
        type: formModel.type,
        department: formModel.department,
        time: formModel.time.replace('T', ' '),
        description: formModel.description,
        impact: formModel.impact,
        solution: formModel.solution
      }
    }
  } else {
    // 新建模式：生成新报告ID
    const date = new Date()
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
    const newReportId = `EXC-${year}-${month}${day}-${randomNum}`

    // 创建新异常报告对象
    const newReport = {
      id: newReportId,
      title: formModel.title,
      type: formModel.type,
      time: formModel.time.replace('T', ' '),
      status: '待处理',
      reporter: '管理员',
      department: formModel.department,
      manager: '',
      description: formModel.description,
      impact: formModel.impact,
      solution: formModel.solution,
      planAdjust: '',
      images: [],
      records: []
    }

    // 添加到数组开头，实现最新报告置顶显示
    exceptionReports.value.unshift(newReport)
  }

  // 关闭表单模态框
  closeFormModal()

  // 显示成功提示
  alert(isEditMode.value ? '异常报告编辑成功！' : '新异常报告创建成功，已实时更新列表！')
}

const openPlanAdjustModal = () => {
  showPlanAdjustModal.value = true
}

const closePlanAdjustModal = () => {
  showPlanAdjustModal.value = false
}

const applyFilters = () => {
  // 筛选逻辑已在computed中实现
}

const resetFilters = () => {
  statusFilter.value = 'all'
  typeFilter.value = 'all'
  deptFilter.value = 'all'
  searchText.value = ''
}

const initChart = () => {
  if (!exceptionChart.value) return

  // 统计实际异常类型分布
  const typeCount = {
    '设备故障': 0,
    '质量问题': 0,
    '物料短缺': 0,
    '人员问题': 0,
    '其他': 0
  }

  exceptionReports.value.forEach(report => {
    if (typeCount.hasOwnProperty(report.type)) {
      typeCount[report.type]++
    }
  })

  new Chart(exceptionChart.value, {
    type: 'doughnut',
    data: {
      labels: ['设备故障', '质量问题', '物料短缺', '人员问题', '其他'],
      datasets: [{
        data: [
          typeCount['设备故障'],
          typeCount['质量问题'],
          typeCount['物料短缺'],
          typeCount['人员问题'],
          typeCount['其他']
        ],
        backgroundColor: [
          '#165DFF',
          '#00B42A',
          '#FF7D00',
          '#F53F3F',
          '#86909C'
        ],
        borderWidth: 0
      }]
    },
    options: {
      cutout: '70%',
      plugins: {
        legend: {
          position: 'bottom',
          labels: {
            usePointStyle: true,
            padding: 20
          }
        }
      }
    }
  })
}

// 生命周期钩子
onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

// 返回到仪表盘的函数（可选）
const backToDashboard = () => {
  router.push('/')
}
</script>

<style scoped>
@import url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css');

.content-auto {
  content-visibility: auto;
}

.sidebar-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  /* 12px, 对应 Tailwind 的 gap-3 */
  padding-left: 1rem;
  /* 16px, px-4 */
  padding-right: 1rem;
  padding-top: 0.75rem;
  /* 12px, py-3 */
  padding-bottom: 0.75rem;
  color: #6B7280;
  /* text-secondary（假设是 gray-500） */
  background-color: transparent;
  border-radius: 0.5rem;
  /* rounded-lg */
  transition: all 0.2s ease-in-out;
}

.sidebar-item:hover {
  background-color: rgba(59, 130, 246, 0.1);
  /* hover:bg-primary/10（假设 primary 是 blue-500） */
  color: #3B82F6;
  /* hover:text-primary */
}

.sidebar-item.active {
  background-color: rgba(59, 130, 246, 0.1);
  /* bg-primary/10 */
  color: #3B82F6;
  /* text-primary */
  font-weight: 500;
  /* font-medium */
}

.card-shadow {
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  /* shadow-sm */
  transition: box-shadow 0.3s ease;
}

.card-shadow:hover {
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  /* hover:shadow-md */
}

.btn-primary {
  background-color: #3B82F6;
  /* bg-primary */
  color: white;
  padding: 0.5rem 1rem;
  /* px-4 py-2 */
  border-radius: 0.5rem;
  /* rounded-lg */
  border: none;
  transition: all 0.2s ease-in-out;
  cursor: pointer;
}

.btn-primary:hover {
  background-color: #3B82F6cc;
  /* hover:bg-primary/90 */
}

.btn-outline {
  background-color: transparent;
  color: #3B82F6;
  /* text-primary */
  padding: 0.5rem 1rem;
  border: 1px solid #3B82F6;
  /* border border-primary */
  border-radius: 0.5rem;
  transition: all 0.2s ease-in-out;
  cursor: pointer;
}

.btn-outline:hover {
  background-color: rgba(59, 130, 246, 0.1);
  /* hover:bg-primary/10 */
}

.btn-danger {
  background-color: #EF4444;
  /* bg-danger（假设是 red-500） */
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 0.5rem;
  border: none;
  transition: all 0.2s ease-in-out;
  cursor: pointer;
}

.btn-danger:hover {
  background-color: #EF4444cc;
  /* hover:bg-danger/90 */
}

.dropdown-item {
  display: block;
  padding: 0.5rem 1rem;
  /* px-4 py-2 */
  font-size: 0.875rem;
  /* text-sm */
  color: inherit;
  transition: background-color 0.2s ease;
  text-decoration: none;
  /* 防止 a 标签下划线 */
}

.dropdown-item:hover {
  background-color: #f3f4f6;
  /* hover:bg-gray-100（gray-100） */
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}

/* 主界面样式 */
.app-container {
  display: flex;
  min-height: 100vh;
}

.main-content {
  padding: 2rem;
  overflow-y: auto;
}

element.style {}

.btn-primary {
  border-radius: 0.5rem;
  --tw-bg-opacity: 1;
  background-color: #4257f7;
  padding-left: 1rem;
  padding-right: 1rem;
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
  --tw-text-opacity: 1;
  color: rgb(255 255 255 / var(--tw-text-opacity, 1));
  transition-property: all;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 200ms;
}
</style>